﻿using IoTSocket.Core;
using IoTSocket.Sockets;
using JunionRobot;
using JunionRobotManager.Serviecs;
using JunionRobotTaskManager.Extensions;
using JunionRobotTaskManager.Models;
using JunionRobotTaskManager.Repository;
using JunionRobotTaskManager.Utility;
using K4os.Compression.LZ4.Internal;
using LazyCache;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Redbus.Interfaces;
using System.Diagnostics;
using System.Net.NetworkInformation;

namespace JunionRobotTaskManager.Services
{
    public class RobotMonitorService : BackgroundService
    {
        private readonly System.Timers.Timer connectTimerManager = new System.Timers.Timer(2000);
        private readonly ConcurrentList<Robot> disconnRobots = new ConcurrentList<Robot>();
        #region Field
        private readonly ILogger<RobotMonitorService> _logger;//日志记录

        private readonly IEventBus _eventBus;//事件监控

        private readonly IServiceProvider _serviceProvider;//服务提供

        private readonly IOptionsMonitor<SystemInfo> _options;//系统设置

        private readonly IAppCache _cache; //缓存

        private readonly IHubContext<ReportHub> _hubContext; //SignalR

        private readonly ParkService parkService;

        private Dictionary<string, int> valuePairs = new Dictionary<string, int>();//分步的数目

        private List<Robot> robots = null;

        private List<Park> parks = null;

        private List<Dock> docks = null;



        private List<TransferPort> transferPorts = null;

        private List<Job> untreatedCharingJobs = null;//软件重启后未处理的充电任务



        #endregion

        #region ctor

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="eventBus"></param>
        /// <param name="cache"></param>
        /// <param name="hubContext"></param>
        /// <param name="options"></param>
        /// <param name="serviceProvider"></param>
        public RobotMonitorService(ILogger<RobotMonitorService> logger,
            IEventBus eventBus,
            IAppCache cache,
             IHubContext<ReportHub> hubContext,
            IOptionsMonitor<SystemInfo> options,
            IServiceProvider serviceProvider,
            ParkService parkService)
        {
            this._eventBus = eventBus;
            this._logger = logger;
            this._serviceProvider = serviceProvider;
            this._options = options;
            this._cache = cache;
            this._hubContext = hubContext;
            this.parkService = parkService;
            #region
            InitialBasicInfo("All");  //查找所有的信息
            _eventBus.Subscribe<BusMessage>(x =>
            {
                if (x.Key == "Robot")
                {

                    switch (x.Action)
                    {
                        case Operation.Add:

                            robots.Add(x.Data as Robot);
                            //disconnRobots.Add(x.Data as Robot);
                            break;
                        case Operation.Update:
                            var robot = robots.FirstOrDefault(d => d.Id == (x.Data as Robot).Id);
                            robot.Close();
                            robots.Remove(robot);
                            robots.Add(x.Data as Robot);
                            //if ((x.Data as Robot).Enable)
                            //    disconnRobots.Add(x.Data as Robot);
                            break;
                        case Operation.Delete:
                            var deletingrobot = robots.FindAll(d => ((string[])x.Data).Contains(d.Id));
                            foreach (var item in deletingrobot)
                            {
                                item.Close();

                            }
                            //disconnRobots.RemoveAll(d => ((string[])x.Data).Contains(d.Id));
                            robots.RemoveAll(d => ((string[])x.Data).Contains(d.Id));
                            break;

                        default:
                            break;
                    }
                    _cache.Add("Robots", robots, new MemoryCacheEntryOptions() { Priority = CacheItemPriority.NeverRemove });

                }
                else
                {
                    InitialBasicInfo(x.Key);
                }


            });
            //connectTimerManager.Elapsed += ConnectTimerManager_Elapsed;
            //connectTimerManager.Start();
            #endregion
        }
        #endregion

        #region Event

        /// <summary>
        /// 机器人断开连接事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Robot_Disconnected(object sender, string e)
        {
            var client = sender as JnSocket;

            _logger.LogInformation("The robot {0}  has disconencted...", client.IP);
        }


        /// <summary>
        /// 机器人连接成功事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Robot_Connected(object sender, string e)
        {
            var client = sender as JnSocket;
            _logger.LogInformation("The robot {0}  has connected success......", client.IP);
        }


        /// <summary>
        /// 机器人重连管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConnectTimerManager_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            connectTimerManager.Stop();
            try
            {
                if (disconnRobots.Count > 0)
                {

                    disconnRobots.ForEach(x =>
                    {

                        x.Close();
                        if (x.Enable)
                        {
                            x.Connected -= Robot_Connected;
                            x.Connected += Robot_Connected;
                            x.Disconnected -= Robot_Disconnected;
                            x.Disconnected += Robot_Disconnected;

                            Thread.Sleep(200);
                            x.Connect(x.IP, x.Port);
                            _logger.LogInformation($"The robot ({x.IP}-{x.Port}) now begin conenct....");
                        }
                    });
                }
                disconnRobots.RemoveAll(x => x.IsConnected);

            }
            catch (Exception ex)
            {

                _logger.LogError("Connect robot error,the error info is:{0}", ex.Message);
            }

            connectTimerManager.Start();
        }
        #endregion


        /// <summary>
        /// 主任务
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            List<Job> pendingJobs = null;
            var calibration_lock = CalibrationLockSingleton.GetInstance();
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    using (var scope = _serviceProvider.CreateScope())
                    {
                        #region【1】查找可用任务
                        IJobRepoitory jobRepository = scope.ServiceProvider.GetService<IJobRepoitory>();

                        pendingJobs = jobRepository.Query(x => x.Status == TaskState.Pending && x.Type != TaskType.Charge);
                        if (DateTime.Now.Second % 3 == 0)
                        {
                            //发送机器人信息
                            await _hubContext.Clients.All.SendAsync("RobotInfo", robots);
                            //发送任务信息
                            var jobs = jobRepository.Query(x => x.CreateTime.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"));
                            valuePairs["total"] = jobs.Count(x => (DateTime.Now.Date == x.CreateTime.Date));
                            valuePairs["cancel"] = jobs.Count(x => DateTime.Now.Date == x.UpdateTime?.Date && (x.Status == TaskState.Abort || x.Status == TaskState.Canceled));
                            valuePairs["complete"] = jobs.Count(x => DateTime.Now.Date == x.UpdateTime?.Date && x.Status == TaskState.Complete);
                            valuePairs["pending"] = jobs.Count(x => DateTime.Now.Date == x.UpdateTime?.Date && x.Status == TaskState.Pending);
                            await _hubContext.Clients.All.SendAsync("TaskInfo", valuePairs);

                        }

                        #endregion
                        #region【2】寻找可用机器人

                        foreach (var item in robots.Where(x=>x.Enable))
                        {
                            try
                            {
                              
                                item.CalibrationInfo.CalibrationSettings = _options.CurrentValue.CalibrationSettings;
                                if (item.IsConnected)
                                {
                                    if (item.CurrentJob == null)
                                    {
                                        item.IdleTime = item.IdleTime == null ? DateTime.Now : item.IdleTime;
                                        item.IsAvailable = _options.CurrentValue.AvailableStatus.Contains(item.Status);

                                        if (!item.CalibrationInfo.IsCalibrating && !calibration_lock.IsLock)
                                        {
                                            if (item.CalibrationInfo.Enable())
                                            {
                                                calibration_lock.IsLock = true;

                                                item.IsAvailable = false;
                                                var availableDocks = _options.CurrentValue.IsRegionCheck ? docks.Where(x => x.Region.Contains(item.Region) && !x.IsOccupied).ToList() : docks.Where(x => !x.IsOccupied).ToList();
                                                item.ResetPark(scope, parks).IsNeedCharge(scope, _logger, availableDocks, _options.CurrentValue.IsRegionCheck);
                                            }
                                        }
                                        if (item.Bettery < _options.CurrentValue.MinPower && !item.CalibrationInfo.IsCalibrating)
                                        {
                                            item.IsAvailable = false;
                                            var availableDocks = _options.CurrentValue.IsRegionCheck ? docks.Where(x => x.Region.Contains(item.Region) && !x.IsOccupied).ToList() : docks.Where(x => !x.IsOccupied).ToList();
                                            //IsNeedCharge改为了不做电量判断，在调用前判断当前电量是否需要充电 
                                            //ResetPark改为不判断是否有任务
                                            _logger.LogInformation("The robot ({0}) need to minpower dock", item.IP);
                                            item.IsNeedCharge(scope, _logger, availableDocks, _options.CurrentValue.IsRegionCheck);
                                        }
                                        else if (item.Bettery < _options.CurrentValue.IdleNotChargePower && !item.CalibrationInfo.IsCalibrating)
                                        {
                                            if (item.IdleTime != null &&
                                            _options.CurrentValue.IdleCharginTime != 0 &&
                                            (DateTime.Now - item!.IdleTime).Value.TotalMinutes > _options.CurrentValue.IdleCharginTime
                                            && item.Status.ToLower().Contains("idle"))
                                            {
                                                _logger.LogInformation("The robot ({0}) need to ilde dock", item.IP);
                                                
                                                
                                                  
                                                
                                                var availableDocks = _options.CurrentValue.IsRegionCheck ? docks.Where(x => x.Region.Contains(item.Region) && !x.IsOccupied).ToList() : docks.Where(x => !x.IsOccupied).ToList();
                                                if (availableDocks.Any())
                                                {
                                                    item.IsAvailable = false;

                                                    var park = parks.Find(x => x.IsOccupied && x.RobotId == item.Id);
                                                    if (park != null)
                                                    {
                                                        park.IsOccupied = false;
                                                        park.RobotId = null;
                                                        IParkRepository parkRepository = scope.ServiceProvider.GetService<IParkRepository>();
                                                        await parkRepository.UpdateEntityAsync(park);
                                                    }

                                                    item.IsNeedCharge(scope, _logger, availableDocks, _options.CurrentValue.IsRegionCheck);
                                                }
                                                else
                                                {
                                                    _logger.LogInformation("The robot ({0}) need to ilde dock,can't find idle docks", item.IP);
                                                    item.IsAvailable = true;
                                                }
                                            }

                                        }
                                        item.IsAvailable = item.IsAvailable && !item.CalibrationInfo.IsCalibrating;
                                    }
                                    else if (item.CurrentJob.Type == TaskType.Charge)
                                    {
                                        if (!item.CalibrationInfo.IsCalibrating && !calibration_lock.IsLock)
                                        {
                                            if (item.CalibrationInfo.Enable())
                                            {
                                                calibration_lock.IsLock = true;
                                            }
                                        }
                                        if (item.CalibrationInfo.IsCalibrating)
                                        {
                                            if (item.CalibrationInfo.IsTiming)
                                            {
                                                if (item.CalibrationInfo.IsComplete())
                                                {
                                                    calibration_lock.IsLock = false;
                                                    item.CalibrationInfo.Reset();
                                                    parkService.DealPark(item);
                                                    item.IsAvailable = _options.CurrentValue.AvailableStatus.Contains(item.Status);
                                                }
                                            }
                                            else if (item.Bettery == 100)
                                            {
                                                item.CalibrationInfo.StartTimer();
                                            }
                                        }
                                        else if (item.Bettery >= _options.CurrentValue.MaxPower)  //大于充电上限去park点，防止小车自动脱离充电桩(一般在>95时会发生，可在小车参数中设置)
                                        {
                                            var dock = docks.Find(x => x.Id == item.CurrentJob.Targets.Keys.First());
                                            _logger.LogInformation($"robot({item.IP}) charge to MaxPower {item.Bettery}, release the dock {dock.Id}");
                                            item.CurrentJob.UpdateInfo(scope.ServiceProvider.GetService<IJobRepoitory>(), TaskState.Complete);
                                            dock.ReSetDock(scope.ServiceProvider.GetService<IDockRepository>());
                                            item.CurrentJob = null;
                                            item.JobId = string.Empty;
                                            scope.ServiceProvider.GetService<IRobotRepository>().UpdateEntity(item);

                                            parkService.DealPark(item);
                                            item.IsAvailable = _options.CurrentValue.AvailableStatus.Contains(item.Status);
                                        }
                                        else
                                        {
                                            item.IsAvailable = item.Bettery > _options.CurrentValue.ChargePower;
                                        }
                                        item.IsAvailable = item.IsAvailable && !item.CalibrationInfo.IsCalibrating;
                                    }
                                    else
                                    {
                                        item.IsAvailable = false;
                                        //监视Park点是否未释放，监视是否需要充电，改变可用状态
                                        item.IsNeedCharge(scope, _logger,docks, _options.CurrentValue.IsRegionCheck);
                                    }

                                    //未断线
                                    if ((DateTime.Now.Second % 2 == 0 || item.IsStatusChanged))
                                    {
                                        _logger.LogInformation($"***************The robot IP:{item.IP} status:{item.Status},Mode:{item.Mode},bettery:{item.Bettery},IsAvailable:{item.IsAvailable},IldeTime is:{item.IdleTime}*******");
                                        _logger.LogInformation($"***************IP:{item.IP}  current job {item.CurrentJob?.ToString() ?? "is empty"}*******");
                                    }
                                }
                                else
                                {
                                    if (!item.IsReconecting)
                                    {
                                        _logger.LogInformation($"robot({item.Id}-{item.IP}) ready reconnect");
                                        TaskFactory taskFactory = new TaskFactory(TaskCreationOptions.LongRunning,TaskContinuationOptions.None);
                                        taskFactory.StartNew(() =>
                                        {
                                            item.IsReconecting = true;
                                            item.Close();
                                            item.Connect(item.IP, item.Port);
                                            item.IsReconecting = false;
                                        });
                                        _logger.LogInformation($"robot({item.Id}-{item.IP}) is reconnecting");
                                    }
                                    //if (!disconnRobots.Contains(item))
                                    //{
                                    //    _logger.LogInformation($"The robot disconencted, now ({item.IP}) Add to disconect Robots");
                                    //    disconnRobots.Add(item);
                                    //}
                                    //if (!item.IsReconnecting)
                                    //{
                                    //    item.IsReconnecting = true;
                                    //    item.Close();
                                    //    item.IsAvailable = false;
                                    //    await Task.Run(() =>
                                    //    {
                                    //        item.Connect(item.IP, item.Port);
                                    //    });
                                    //    item.IsReconnecting = false;
                                    //}
                                }
                            }
                            catch (Exception ex)
                            {

                                _logger.LogError($"Monitor Robot({item.IP}) occurs error,The error info is:{ex}");
                            }
                        };
                        #endregion
                        #region 【3】分配任务

                        AssignJob(pendingJobs, scope);
                        #endregion

                    }
                }
                catch (Exception ex)
                {

                    _logger.LogError($"RobotMonitorService occurs error,the error info is:{ex} ");
                }


                await Task.Delay(1000, stoppingToken);
            }


        }




        #region private Method



        /// <summary>
        /// 分配任务
        /// </summary>
        private void AssignJob(List<Job> pendingJobs, IServiceScope scope)
        {

            if (pendingJobs.Count > 0)
            {
                #region 接料任务

                var getJobs = (from job in pendingJobs
                               orderby job.Priority descending
                               orderby job.CreateTime
                               where job.Type != TaskType.Put
                               select job);

                IntervalLoggerHelper.Logger(_logger, 3, $"---------The Get and PickUp total count is: {getJobs.Count()}--------- ");



                foreach (var job in getJobs)
                {
                    //List<Robot> idleGetRobots = robots.Where(x => x.IsAvailable|| x.Id== "SMT-AGVD-002").ToList();
                    List<Robot> idleGetRobots = robots.Where(x => x.IsAvailable).ToList();
                    //【1】区域校验
                    var port = transferPorts.Where(x => x.Id == job.CurrentTarget).FirstOrDefault();
                    if (_options.CurrentValue.IsRegionCheck)
                    {
                        idleGetRobots = robots.Where(x => x.Region == (port?.Region ?? "")).ToList();
                        if (idleGetRobots.Count == 0)
                        {
                            continue;
                        }
                    }

                    //【2】指定筛选
                    if (job.AssignRobots?.Length > 0) //没有指定机器人IP
                    {
                        idleGetRobots = idleGetRobots.Where(x => job.AssignRobots.Contains(x.Id) && x.IsAvailable).ToList();
                        if (idleGetRobots.Count == 0)
                            continue;
                    }
                    //【3】物料筛选
                    if (_options.CurrentValue.IsMaterialCheck)
                    {
                        idleGetRobots = idleGetRobots.Where(x => job.MaterialCodes.All(jm => x.Payloads.Any(rm => rm == jm))).ToList();
                        if (idleGetRobots.Count == 0)
                            continue;

                    }
                    foreach (var item in idleGetRobots.Where(x => x.Floor == port.Floor))
                    {
                        _logger.LogInformation($"**************job:{job.Id}***********robot:{item.Id}********************************");
                    }
                    Robot robot = null;
                    //if (idleGetRobots.Where(x => x.IsAvailable && x.Floor == port.Floor).Count() > 0)
                    //{
                    //    robot = idleGetRobots.Where(x => x.IsAvailable && x.Floor == port.Floor).OrderBy(x => Math.Pow(x.PosX - port.XPosition, 2) + Math.Pow(x.PosY - port.YPosition, 2)).ThenByDescending(x => x.Bettery).FirstOrDefault();
                    //}
                    //else
                    //{
                    //    robot = idleGetRobots.Where(x => x.IsAvailable).OrderBy(x => Math.Pow(x.PosX - port.XPosition, 2) + Math.Pow(x.PosY - port.YPosition, 2)).ThenByDescending(x => x.Bettery).FirstOrDefault();
                    //}
                    //var robot = idleGetRobots.Where(x => x.IsAvailable || x.Id == "SMT-AGVD-002").OrderByDescending(x => x.Floor == port.Floor).ThenBy(x => Math.Pow(x.PosX - port.XPosition, 2) + Math.Pow(x.PosY - port.YPosition, 2)).ThenByDescending(x => x.Bettery).FirstOrDefault();
                    robot = idleGetRobots.Where(x => x.IsAvailable).OrderByDescending(x => x.Floor == port.Floor).ThenBy(x => Math.Pow(x.PosX - port.XPosition, 2) + Math.Pow(x.PosY - port.YPosition, 2)).ThenByDescending(x => x.Bettery).FirstOrDefault();

                    //var robot = idleGetRobots.Where(x => x.IsAvailable || x.Id == "SMT-AGVD-002").OrderBy(x => Math.Pow(x.PosX - port.XPosition, 2) + Math.Pow(x.PosY - port.YPosition, 2)).ThenByDescending(x => x.Bettery).FirstOrDefault();
                    if (robot != null)
                    {
                        if (robot.BeginJob(job, scope, docks, _logger))
                        {
                            ReportToMes(robot, "Assign");
                            if (parks.Exists(p => p.RobotId == robot.Id))
                            {
                                var park = parks.Find(p => p.RobotId == robot.Id);
                                park.IsOccupied = false;
                                park.RobotId = null;
                                _logger.LogInformation("The robot {0} release the park {1}",robot.IP,park.Id);
                            }
                            if (docks.Exists(p => p.RobotId == robot.Id))
                            {
                                var dock = docks.Find(p => p.RobotId == robot.Id);
                                dock.IsOccupied = false;
                                dock.RobotId = null;
                                _logger.LogInformation("The robot {0} release the dock {1}", robot.IP, dock.Id);
                            }
                        }
                    }
                    else
                        _logger.LogInformation("After filter condition,there is no available robots to excute geting job");



                }

                #endregion

                #region 送料任务



                if (pendingJobs.Any(x => x.Type == TaskType.Put))
                {

                    //筛选机器人
                    var availableRobots = from robot in robots
                                          where robot.CurrentJob != null && robot.CurrentJob.Type == TaskType.Get &&
                                          (robot.CurrentJob.Status == TaskState.Complete || robot.CurrentJob.Status == TaskState.Abort)
                                          && robot.Status.ToLower().Contains("idle")
                                          select robot;

                    var putJobs = (from job in pendingJobs
                                   orderby job.Priority descending
                                   orderby job.CreateTime
                                   where job.Type == TaskType.Put
                                   select job);

                    IntervalLoggerHelper.Logger(_logger, 3, $"-------------Begin Assigned Put job. There is {putJobs.Count()} putjob ------------- ");



                    foreach (var robot in availableRobots)
                    {

                        //【1】筛选符合需要送的任务
                        if (_options.CurrentValue.IsMaterialCheck)
                        {
                            var job = putJobs.Where(x => robot.CurrentJob.MaterialCodes.All(jm => x.MaterialCodes.Any(rm => rm == jm))).
                                              Where(x => x.Status == TaskState.Pending).FirstOrDefault();
                            if (job != null)
                            {
                                var result = robot.BeginJob(job, scope, docks, _logger);
                                if (result)
                                {
                                    ReportToMes(robot, "Assign");
                                    if (parks.Exists(p => p.RobotId == robot.Id))
                                    {
                                        var park = parks.Find(p => p.RobotId == robot.Id);
                                        park.IsOccupied = false;
                                        park.RobotId = null;
                                    }
                                }
                                continue;
                            }
                        }
                        else
                        {
                            var result = robot.BeginJob(putJobs.Where(x => x.Status == TaskState.Pending).First(), scope, docks, _logger);
                            if (result)
                            {
                                ReportToMes(robot, "Assign");
                                if (parks.Exists(p => p.RobotId == robot.Id))
                                {
                                    var park = parks.Find(p => p.RobotId == robot.Id);
                                    park.IsOccupied = false;
                                    park.RobotId = null;
                                }
                            }
                        }


                    }


                }
                #endregion
            }

            if (robots.Any(x => x.CurrentJob?.Type == TaskType.PickUp))
            {
                var watingRobots = robots.Where(x => x.CurrentJob?.Type == TaskType.PickUp);
                foreach (var item in watingRobots)
                {
                    if (item.Status?.ToLower().Contains("idle") ?? false && item.CurrentJob.Status != TaskState.Complete)
                    {
                        var portRepository = scope.ServiceProvider.GetService<ITransferPortRepository>();
                        var port = portRepository.Find(x => x.Id == item.CurrentJob.CurrentTarget);
                        // item.RoutesWithConfirm(item.CurrentJob.CurrentTarget);
                        var route = item.Floor == port.Floor ? $"{port.Id}" : $"{item.Floor}F-{port.Floor}F_{port.Id}";
                        item.ExcutePath(route, item.CurrentJob.Id);
                        _logger.LogInformation($"The robot({item.IP}) status is:{item.Status},now go to next target:{item.CurrentJob.CurrentTarget}");
                    }
                }



            }



        }





        /// <summary>
        /// 汇报给MES
        /// </summary>
        /// <param name="isComplete"></param>
        /// <param name="robot"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private bool ReportToMes(Robot robot, string status)
        {

            string reportinfo = "";
            string url = "";

            {
                var data = new
                {
                    Command = "Info",
                    Id = robot.CurrentJob.Id,
                    Robot = robot.Id,
                    DockType = robot.CurrentJob.Targets[robot.CurrentJob.CurrentTarget].ToLower() == "put" ? 2 : 1,
                    Status = status,
                    Target = robot.CurrentJob.CurrentTarget,
                    Remark = ""
                };
                url = _options.CurrentValue.DeliveryUrl;
                reportinfo = JsonConvert.SerializeObject(data);
            }

            _logger.LogInformation($"Report the  mes data is:{reportinfo}");
            ResponseResult apiResult = new ResponseResult() { Data = "failed" };
            try
            {
#if !DEBUG
                string responseData = responseData = HttpHelper.RequestPost(url, reportinfo);
                _logger.LogInformation($"Receive the mes data is:{responseData}");
                apiResult = JsonConvert.DeserializeObject<ResponseResult>(responseData);
   
                if ((apiResult != null && apiResult.Data.ToLower() == "succeed"))
                {
                    return true;
                }
                else
                {
                    _logger.LogInformation($"Send to the mes data failed ");
                    return false;
                }
#else
                return true;
#endif

            }
            catch (Exception ex)
            {
                _logger.LogError($"Report mes message occurs error,the error info is:{ex.Message}");
                return false;
            }


        }



        /// <summary>
        /// 初始化基础信息
        /// </summary>
        /// <param name="keyName">基础信息的名称</param>
        /// <returns></returns>
        private void InitialBasicInfo(string keyName)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                if (keyName == "All")
                {
                    //机器人信息
                    IRobotRepository robotRepository = scope.ServiceProvider.GetService<IRobotRepository>();
                    robots = robotRepository.QueryRelated();
                    robots.ForEach(x =>
                    {
                        if (x.CurrentJob != null && x.CurrentJob.Type == TaskType.Charge)
                        {
                            IJobRepoitory jobRepository = scope.ServiceProvider.GetService<IJobRepoitory>();
                            if (!jobRepository.CheckExist(j => j.Id == x.CurrentJob.Id))
                            {
                                x.CurrentJob = null;
                                x.JobId = string.Empty;
                            }
                        }
                        if (x.CurrentJob?.Status == TaskState.Complete)
                        {
                            x.CurrentJob = null;
                            x.JobId = string.Empty;
                        }
                    });



                    _cache.Add("Robots", robots, new MemoryCacheEntryOptions() { Priority = CacheItemPriority.NeverRemove });

                    //Ports点信息
                    ITransferPortRepository transferPortRepository = scope.ServiceProvider.GetService<ITransferPortRepository>();
                    transferPorts = transferPortRepository.Query();
                    _cache.Add("Ports", transferPortRepository.Query(), new MemoryCacheEntryOptions() { Priority = CacheItemPriority.NeverRemove });

                    //Park点信息
                    IParkRepository parkRepository = scope.ServiceProvider.GetService<IParkRepository>();
                    parks = parkRepository.Query();
                    _cache.Add("Parks", parks, new MemoryCacheEntryOptions() { Priority = CacheItemPriority.NeverRemove });

                    //充电桩信息
                    IDockRepository dockRepository = scope.ServiceProvider.GetService<IDockRepository>();
                    docks = dockRepository.Query();

                    IJobRepoitory jobRepoitory = scope.ServiceProvider.GetService<IJobRepoitory>();
                    untreatedCharingJobs = jobRepoitory.Query().Where(x => x.Type == TaskType.Charge
                    && x.Status != TaskState.Complete
                   ).ToList();
                    _cache.Add("Docks", docks, new MemoryCacheEntryOptions() { Priority = CacheItemPriority.NeverRemove });



                }
                else if (keyName == "Dock")
                {
                    //充电桩信息
                    IDockRepository dockRepository = scope.ServiceProvider.GetService<IDockRepository>();
                    docks = dockRepository.Query();
                    _cache.Add("Docks", dockRepository.Query(), new MemoryCacheEntryOptions() { Priority = CacheItemPriority.NeverRemove });
                }
                else if (keyName == "Park")
                {
                    //Park点信息
                    IParkRepository parkRepository = scope.ServiceProvider.GetService<IParkRepository>();
                    parks = parkRepository.Query();
                    _cache.Add("Parks", parkRepository.Query(), new MemoryCacheEntryOptions() { Priority = CacheItemPriority.NeverRemove });
                }
                else if (keyName == "Port")
                {
                    //Ports点信息
                    ITransferPortRepository transferPortRepository = scope.ServiceProvider.GetService<ITransferPortRepository>();
                    transferPorts = transferPortRepository.Query();
                    _cache.Add("Ports", transferPortRepository.Query(), new MemoryCacheEntryOptions() { Priority = CacheItemPriority.NeverRemove });
                }
            }

        }






        #endregion
    }
}
